#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import gettext
import time
import dbus
import cgi
import sys
import os

# Template engine
from Cheetah.Template import Template
import cgitb; cgitb.enable()

# Translation function
_ = gettext.gettext

# Set DBUS environment
os.environ['DBUS_SESSION_BUS_ADDRESS'] = 'unix:path=/var/run/dbus/system_bus_socket'

class InterfaceException(Exception):
    pass

class Widget:
    def __init__(self, template):
        self.templ = Template(file=template)

    def render(self):
        pass

    def __str__(self):
        self.render()
        return str(self.templ)

class Label(Widget):
    def __init__(self, name, text='', style=None):
        Widget.__init__(self, '../tmpl/label.tmpl')
        self.templ.name = name
        self.templ.text = text
        if style==None: style = 'generic'
        self.templ.style = style

    def settext(self, value):
        self.templ.text = value

    def gettext(self):
        return self.templ.text

    text = property(None, settext)

class Cam:
    def getname(self):
        lab = Label('cam'+str(self.id), self.name, 'camname')
        return str(lab)
        
    editablename = property(getname, None)

class Agent:
    ref = None

    @staticmethod
    def getAgent():
        if Agent.ref==None:
            bus = dbus.SessionBus()
            remote_object = bus.get_object("org.security.agent", "/org/security/agent/gui")
            Agent.ref = dbus.Interface(remote_object, "org.security.agent")
        return Agent.ref

    @staticmethod
    def queryMovies(start, protected='all', reviewed='all', started='all'):
        protected_q = {'all':-1,'yes':'1','no':0}[protected]
        reviewed_q = {'all':-1,'yes':'1','no':0}[reviewed]
        started_q = {'automatic':'a','manual':'m','continious':'c','all':'t'}[started]

        a = Agent.getAgent()
        t = a.queryMovies(start, 0, 10, protected_q, reviewed_q, started_q)
        res = []
        for result in t:
            tt = time.gmtime(result[2])
            a = {}
            a['cam'] = result[1].encode('latin-1')
            a['day'] = time.strftime('%d / %m / %Y',tt)
            a['hour'] = time.strftime('%H:%M',tt)
            a['duration'] = result[3]
            a['path'] = result[7].encode('latin-1')
            res.append(a)
        return res

    @staticmethod
    def getCams():
        a = Agent.getAgent()
        syscams = a.getCameraList()
        cams = []
        for syscam in syscams:
            c = Cam()
            c.id = syscam['camid'].encode('latin-1')
            c.enabled = (int(syscam['enabled'])==1)
            c.name = syscam['nom'].encode('latin-1')
            cams.append(c)
        return cams

    @staticmethod
    def setCameraName(camID, name):
        a = Agent.getAgent()
        a.setCameraName(camID, name)
        
    @staticmethod
    def setCamEnabled(camID, enabled):
        a = Agent.getAgent()
        if enabled:
            a.enableCamera(camID)
        else:
            a.disableCamera(camID)

    @staticmethod
    def setCamProps(idcam, sensib, fps, cam):
        a = Agent.getAgent()
        a.setCamProperties(idcam, sensib, fps, cam)

    @staticmethod
    def getCamProps(idcam):
        a = Agent.getAgent()
        return a.getCamProperties(idcam)
    
    @staticmethod
    def setSystemProps(mail, space, durat):
        a = Agent.getAgent()
        a.setAdminMail(mail)
        a.setMaxSpace(int(space))
        a.setMaxDuration(durat)

    @staticmethod
    def getSystemProps():
        a = Agent.getAgent()
        mail = a.getAdminMail()
        space = a.getMaxSpace()
        durat = a.getMaxDuration()
        return {'mail':mail, 'space':space, 'durat':durat}

class Tab:
    def __init__(self, name, title, content):
        self.name = name
        self.title = title
        self.content = content
        self.active = False

    def __str__(self):
        return str(self.content)

class TabContent:
    def __init__(self, template, form):
        self.templ = Template(file=template)
        self.form = form
    
    def render(self):
        pass

    def __str__(self):
        self.render()
        return str(self.templ)

class MonitorTab(TabContent):
    def render(self):
        self.templ.cams = Agent.getCams()

class MainConfigTab(TabContent):
    def render(self):
        if self.form.has_key('submit') and self.form['submit'].value=='conf':
            mail = self.form['email'].value
            maxdur = self.form['maxduration'].value
            maxsize = self.form['maxspace'].value
            Agent.setSystemProps(mail, maxsize, maxdur)

        self.templ.data = Agent.getSystemProps()
    
        self.templ.strings = {}
        self.templ.strings['maxspace'] = _('Max space in disk (MB)')
        self.templ.strings['maxduration'] = _('Max video duration (secs)')
        self.templ.strings['adminmail'] = _('Administrator mail')
        self.templ.strings['save'] = _('Save')

        self.templ.title = _('Main Configuration')
        self.templ.sectiona = _('Main properties')
        self.templ.sectionb = _('System cameras')

        self.templ.camtab = 'dcam'
        self.templ.cams = Agent.getCams()

class CamConfigTab(TabContent):
    def render(self):
        if self.form.has_key('submit') and self.form['submit'].value=='cam':
            camID = self.form['camid'].value
            camName = self.form['camname'].value
            if self.form.has_key('camenabled'):
                camEnabled = 1
            else: 
                camEnabled = 0
            camSched = (self.form['camsched'].value==1)
            #camSStart = self.form['sched_start'].value
            #camSEnd = self.form['sched_end'].value
            camSensib = float(self.form['camsensib'].value)/10
            camFps = float(self.form['camfps'].value)
            camMode = int(self.form['cammode'].value)
    
            a = Agent.getAgent()
            a.setCamProperties(camID, camEnabled, camFps, camMode, camName, camSensib)

        self.templ.strings = {}
        self.templ.strings['submit'] = _('Save')

        camid = self.form['camid'].value
        cam = Agent.getCamProps(camid)
        cam['enabled'] = (int(cam['enabled'])==1)
        self.templ.asa = str(cam)
        self.templ.cam = cam
        self.templ.clock = ['%02d:00'%(i) for i in range(24)]
        s = float(cam['threshold'])
        self.templ.sensib = [{'a':'%d'%(i),'b':'%d'%(i*10),'c':((i+1)/10.-0.02)>s>((i-1)/10.+0.02)} for i in range(0,11)]
        self.templ.fps = [{'a':'30','b':'30.0','c':(float(cam['fps'])==30.0)},{'a':'25','b':'25.0','c':(float(cam['fps'])==25.0)},{'a':'10','b':'10.0','c':(float(cam['fps'])==10.0)},{'a':'5','b':'5.0','c':(float(cam['fps'])==5.0)},{'a':'1','b':'1.0','c':(float(cam['fps'])==1.0)},{'a':'1/2','b':'0.5','c':(float(cam['fps'])==0.5)},{'a':'1/5','b':'0.2','c':(float(cam['fps'])==0.2)}]

class HistoryTab(TabContent):
    def render(self):
        self.templ.strings = {}
        self.templ.strings['startday'] = _('Start day')
        self.templ.strings['day'] = _('day')
        self.templ.strings['month'] = _('month')
        self.templ.strings['year'] = _('year')
        self.templ.strings['camselect'] = _('Select camera')
        self.templ.strings['started'] = _('Started')
        self.templ.strings['filter'] = _('Filter')
        self.templ.strings['results'] = _('Results')
        
        self.templ.form_days = [str(i) for i in range(1,32)]
        self.templ.form_months = [str(i) for i in range(1,13)]
        self.templ.form_years = [str(i) for i in range(2000,2008)]
        self.templ.cams = Agent.getCams()

        if self.form.has_key('submit'):
            day = self.form['day'].value
            month = self.form['month'].value
            year = self.form['year'].value
            started = self.form['started'].value
            protected = self.form['protected'].value
            reviewed = self.form['reviewed'].value
            t = time.strptime(str(day)+' '+str(month)+' '+str(year), '%d %m %Y')
            tini = int(time.mktime(t))
            self.templ.results = Agent.queryMovies(tini, protected, reviewed, started)
        else:
            self.templ.results = Agent.queryMovies(2**31)

class Interface:
    def __init__(self):
        self.form = cgi.FieldStorage()
        self.main_temp = Template(file='../tmpl/main.tmpl')
        self.tabs = {}
        self.active_tab = None

    def render(self):
        # Default tabs
        self.addTab('amonitor',_('Monitor'), MonitorTab('../tmpl/monitor.tmpl', self.form))
        self.addTab('bhistory',_('History'), HistoryTab('../tmpl/history.tmpl', self.form))
        self.addTab('cconfig',_('Main Config.'), MainConfigTab('../tmpl/mainconfig.tmpl', self.form))

        # Set the active tab
        if self.form.has_key('tab'):
            tab = self.form['tab'].value
            # Read if we need a new 
            if tab=='dcam':
                t = self.addTab('dcam',_('Cam Config.'), CamConfigTab('../tmpl/camconfig.tmpl', self.form))
            active_tab = self.tabs[tab]
        else:
            active_tab = self.tabs[self.tabs.keys()[0]]

        active_tab.active = True

        # Set the Main template options
        keys = self.tabs.keys()
        keys.sort()
        self.main_temp.navtabs = [self.tabs[k] for k in keys]
        self.main_temp.content = str(active_tab)
    
    def addTab(self, name, title, content):
        t = Tab(name, title, content)
        self.tabs[name] = t
        return t

    def __str__(self):
        s = 'Content-type: text/html\n\n'
        s += str(self.main_temp)
        return s

main = Interface()
main.render()
print main
